package com.iw.core.security.action;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.iw.adoms.entity.Department;
import com.iw.adoms.service.DepartmentService;
import com.iw.core.orm.PageData;
import com.iw.core.security.entity.Roles;
import com.iw.core.security.entity.Users;
import com.iw.core.security.service.RolesService;
import com.iw.core.security.service.UsersService;
import com.iw.core.utils.EncryptUtils;
import com.iw.core.utils.WebUtils;

@Controller
@RequestMapping("/security/users")
public class UsersAction {

	@Resource
	private RolesService rolesService;
	@Resource
	private UsersService usersService;
	@Resource
	private DepartmentService departmentService;

	@RequestMapping("/list")
	public ModelMap list(HttpServletRequest request) {
		PageData<Users> pageData = new PageData<Users>();
		// 给pageData设置参数
		WebUtils.setPageDataParameter(request, pageData);
		pageData = usersService.find(pageData);
		return new ModelMap(pageData);
	}

	@RequestMapping(value = "/new")
	public String addForm(Model model) {
		commonModel(model);
		model.addAttribute(new Users());
		return "/security/users/input";
	}

	private void commonModel(Model model) {
		List<Roles> rolesList = rolesService.findAll();
		model.addAttribute("rolesList", rolesList);
		List<Department> departmentList = departmentService.findAll();
		model.addAttribute("departmentList", departmentList);
	}

	@RequestMapping(value = "/edit/{id}")
	public String editForm(@PathVariable("id") Integer id, Model model) {
		Users users = usersService.find(id);
		model.addAttribute(users);
		commonModel(model);
		return "/security/users/input";
	}

	@RequestMapping(value = "/repeat")
	@ResponseBody
	public boolean repeat(String account, Integer id) {
		try {
			List<Users> users = usersService.findList("account", account);
			if (users != null && users.size() > 0) {
				if (id != 0) {
					Users u = usersService.find(id);
					if (!u.getAccount().equals(account)) {
						return false;
					}
				} else {
					return false;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

	@RequestMapping(value = "/passwd")
	public String passwd(HttpServletRequest request) {
		return "/security/users/passwd";
	}

	@RequestMapping(value = "/isOldpwd")
	@ResponseBody
	public boolean isOldpwd(Integer uid, String oldpwd) {
		Users u = usersService.find(uid);
		if (u.getPassword().equals(EncryptUtils.md5(oldpwd))) {
			return true;
		} else {
			return false;
		}
	}

	@RequestMapping(value = "/passwd2", method = RequestMethod.POST)
	public String passwd2(Integer uid, HttpServletRequest request, String passwd, Model model) {
		String msg = "";
		try {
			Session session = usersService.getBaseDao().getNewSession();
			Transaction transaction = session.beginTransaction();
			Users users = (Users) session.get(Users.class, uid);
			if (StringUtils.isNotBlank(passwd)) {
				users.setPassword(EncryptUtils.md5(passwd));
				session.update(users);
				msg = "密码修改成功!";
			} else {
				msg = "密码修改失败！";
			}
			transaction.commit();
			session.close();

		} catch (Exception e) {
			e.printStackTrace();
			msg = "密码修改失败！";
		}

		model.addAttribute("msg", msg);
		return "/security/users/passwd";
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(@Valid Users users, BindingResult result, HttpServletRequest request) {
 		if (result.hasErrors()) {
			return "/security/users/input";
		}
		String[] rolesIds = request.getParameterValues("roles.id");
		if (rolesIds != null) {
			Set<Roles> rolesSet = new HashSet<Roles>();
			String addedIds = "";
			for (String rolesId : rolesIds) {
				// 去掉重复的roles id
				if (addedIds.contains(rolesId + ",")) {
					continue;
				} else {
					try {
						Roles roles = rolesService.find(Integer.parseInt(rolesId));
						rolesSet.add(roles);
						addedIds += rolesId + ",";
					} catch (Exception e) {
					}
				}
			}
			users.setRoles(rolesSet);
		}
		if (!users.getPassword().equals(users.getOldPwd())) {
			users.setPassword(EncryptUtils.md5(users.getPassword())); // 根据盐值加密
			// users.setPassword(EncryptUtils.md5(users.getPassword() + "{" + users.getAccount() + "}")); // 根据盐值加密
			users.setOldPwd(users.getPassword());
		}
		if (users.isNew()) {
			usersService.save(users);
		} else {
			usersService.update(users);
		}

		return "redirect:/security/users/list";// 重定向
	}

	@RequestMapping(value = "/delete/{id}")
	public String delete(@PathVariable("id") Integer id) {
		usersService.delete(id);
		return "redirect:/security/users/list";// 重定向
	}

	@RequestMapping(value = "/visible/{id}")
	public String visible(@PathVariable("id") Integer id) {
		usersService.visible(id);
		return "redirect:/security/users/list";// 重定向
	}

	@RequestMapping(value = "/unVisible/{id}")
	public String unVisible(@PathVariable("id") Integer id) {
		usersService.unVisible(id);
		return "redirect:/security/users/list";// 重定向
	}

	@InitBinder
	public void InitBinder(WebDataBinder dataBinder) {
		dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));
	}

}
